package com.share.shareplatform.util;



import com.share.shareplatform.pojo.SecurityUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class AuthorityUtil {
    public static boolean hasAuthorityUtil(String s){
        SecurityUser user = (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Collection<GrantedAuthority> authorities = user.getAuthorities();
        for(GrantedAuthority grantedAuthority:authorities){
            if (grantedAuthority.getAuthority().equals(s)) {
                return true;
            }
        }
        return false;
    }

    public static Long getUserId(){

        SecurityUser user = (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return user.getId();
    }


    public static String authorityCollectionToString(Collection<GrantedAuthority> list){
        StringBuilder builder=new StringBuilder();
        list.forEach(a->{
            builder.append(a+",");
        });
        if(builder.charAt(builder.length()-1)==','){
            builder.deleteCharAt(builder.length()-1);
        }
        return builder.toString();
    }

    public static List<GrantedAuthority> authorityStringToCollection(String authorityString){
        String[] split = authorityString.split(",");
        ArrayList<GrantedAuthority> arrayList=new ArrayList<>();

        for(String s:split){
            GrantedAuthority g=new SimpleGrantedAuthority(s);
            arrayList.add(g);
        }
        return arrayList;
    }
}
